package mybatis.service.impl;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import mybatis.dao.AddressDao;
import mybatis.entity.Address;
import mybatis.service.AddressService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddressServiceImpl implements AddressService {
	@Autowired
	private AddressDao addressDao;
	@Override
	public Map<String, String> getProvcine() {
		List<Map<String, String>> list= addressDao.getProvince();
		Map<String, String> provinceMap = tranformList(list);
		return provinceMap;
	}
	
	public  Map<String,String> tranformList(List<Map<String, String>> list){
		//转换方法
		Map<String, String> map = new TreeMap((s1,s2) -> ((String) s1).compareTo((String)s2));
		if (list != null && !list.isEmpty()) {
			for (Map<String, String> hashMap : list) {
		    	String key = null;
		        String value = null;
		        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
		 	       if ("key".equals(entry.getKey())) {
		 	       		key = (String) entry.getValue();
		           } else if ("value".equals(entry.getKey())) {
		           		//我需要的是int型所以做了如下转换，实际上返回的object应为Long。
		                value = entry.getValue();
		           }     
		        }
		        map.put(key, value);
		    }
		}
		System.out.println(map);
		
		return map;
	}

	@Override
	public Map<String, String> getCity(String id) {
		List<Map<String, String>> list= addressDao.getCity(id);
		System.out.println(list);
		Map<String, String> cityMap = tranformList(list);
		if(cityMap.get("0").endsWith("市")) {
			if(cityMap.get("01") != null) {
				cityMap.put("01","选择区");
			}
			if(cityMap.get("02") != null) {
				cityMap.put("02","选择县");
			}
		}
		cityMap.remove("0");
		System.out.println(cityMap);
		return cityMap;
	}

	@Override
	public Map<String, String> getArea(String pid, String id) {
		List<Map<String, String>> list= addressDao.getArea(pid,id);
		System.out.println(list);
		Map<String, String> areaMap = tranformList(list);
		System.out.println(areaMap);
		return areaMap;
	}

	@Override
	public Map<String, String> getTown(String pid, String cid, String id) {
		List<Map<String, String>> list= addressDao.getTown(pid,cid,id);
		System.out.println(list);
		Map<String, String> townMap = tranformList(list);
		System.out.println(townMap);
		return townMap;
	}

	@Override
	public void add(Address addr) {
		addressDao.add(addr);
	}

	@Override
	public List<Address> findByUid(int id) {
		List<Address> list = addressDao.findByUid(id);
		return list;
	}
}
